package com.h3c.nem.utils;


import com.eos.common.domain.ActiveUser;
import com.h3c.nem.config.CustomHttpServletRequestWrapper;
import com.h3c.nem.entity.TbOfferWorker;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.poi.hssf.usermodel.DVConstraint;
import org.apache.poi.hssf.usermodel.HSSFDataValidation;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFDataValidation;
import org.apache.poi.xssf.usermodel.XSSFDataValidationConstraint;
import org.apache.poi.xssf.usermodel.XSSFDataValidationHelper;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.math.BigDecimal;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@Slf4j
public class CommonUtil {

    public final static ThreadLocal<ActiveUser> userHolder = new ThreadLocal<>();

    public static ActiveUser getActivUser() {
        return userHolder.get();
    }

    /**
     * 产生4位随机数(000000-999999)
     *
     * @return 4位随机数
     */
    public static String getSixRandom() {
        Random random = new Random();
        String fourRandom = random.nextInt(1000000) + "";
        int randLength = fourRandom.length();
        if (randLength < 6) {
            for (int i = 1; i <= 6 - randLength; i++)
                fourRandom = "0" + fourRandom;
        }
        return fourRandom;
    }

    /**
     * 生成员工基本信息在redis中存储的key
     * value的格式为 name,email,direct_dept_id
     *
     * @param workerId
     * @return
     */
    public static String genWorkerRedisKey(String workerId) {
        return "worker_basic_" + workerId;
    }

    /**
     * 生成小程序uid对应登录人基本信息在redis中存储的key
     * value的格式为 LoginUserDTO
     *
     * @param uid
     * @return
     */
    public static String genUidRedisKey(String uid) {
        return "toc_uid_" + uid;
    }

    /**
     * 生成记录登录人对象的key
     * value的格式为 LoginUserDTO
     *
     * @param id
     * @return
     */
    public static String genLoginRedisKey(String id) {
        return "toc_login_" + id;
    }

    public static String getNewStageName(String stageName) {
        if (!StringUtils.isEmpty(stageName)) {
            if (stageName.equals("一档")) {
                return "一档 (6~9级)";
            } else if (stageName.equals("二档")) {
                return "二档 (10~13级)";
            } else if (stageName.equals("三档")) {
                return "三档 (14级及以上)";
            }
        }
        return "";
    }

    public static void removeRow(Sheet sheet, int rowIndex) {
        int lastRowNum = sheet.getLastRowNum();
        if (rowIndex >= 0 && rowIndex < lastRowNum) {
            sheet.shiftRows(rowIndex + 1, lastRowNum, -1);
        }
        if (rowIndex == lastRowNum) {
            Row removingRow = sheet.getRow(rowIndex);
            if (removingRow != null) {
                sheet.removeRow(removingRow);
            }
        }
    }

    public static void setSelectValueForColumn(Sheet sheet, int colNum, String[] selectValues) {
        addValidate2Cell(sheet, 0, 30000, colNum, colNum, selectValues);
    }

    public static void addValidate2Cell(Sheet sheet, int firstRow, int lastRow, int firstCol, int lastCol, String[] selectValues) {
        //值的范围为空，则不添加校验
        if (selectValues == null || selectValues.length == 0)
            return;

        try {
            if (sheet instanceof HSSFSheet) {
                CellRangeAddressList addressList = new CellRangeAddressList(firstRow, lastRow, firstCol, lastCol);
                DVConstraint dvConstraint = DVConstraint.createExplicitListConstraint(selectValues);
                DataValidation dataValidation = new HSSFDataValidation(addressList, dvConstraint);
                dataValidation.setSuppressDropDownArrow(false); //03默认false
                sheet.addValidationData(dataValidation);
            } else if (sheet instanceof XSSFSheet) {
                XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper((XSSFSheet) sheet);
                XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint) dvHelper.createExplicitListConstraint(selectValues);
                CellRangeAddressList addressList = new CellRangeAddressList(firstRow, lastRow, firstCol, lastCol);
                XSSFDataValidation validation = (XSSFDataValidation) dvHelper.createValidation(dvConstraint, addressList);
                validation.setShowErrorBox(true);
                validation.setSuppressDropDownArrow(true); //07默认true
                sheet.addValidationData(validation);
            }
        } catch (Exception e) {
            //log.error("下拉框的选项过多导致出错：java.lang.IllegalArgumentException:String literals in formulas can't be bigger than 255 characters ASCII");
            e.printStackTrace();
        }
    }

    public static PrivateKey getPrivateKey(String privateKey) {

        try {
            byte[] keyBytes;
            keyBytes = Base64.getDecoder().decode(privateKey.getBytes());
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return keyFactory.generatePrivate(keySpec);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Claims parseJWT(String jwtStr, String publicKey) {
        try {
            return Jwts.parser()
                    .setSigningKey(publicKey)
                    .parseClaimsJws(jwtStr)
                    .getBody();
        } catch (Exception e) {
            return null;
        }
    }

    public static String null2Empty(String str) {
        return str == null ? "" : str;
    }

    public static String null2Empty(Object obj) {
        return obj == null ? "" : String.valueOf(obj);
    }

    public static Map constructMapResult(List resultList, int start, int size) {
        List pageResultList = new ArrayList<>();
        for (int i = start; i < resultList.size(); i++) {
            if (size-- > 0) {
                Object dto = resultList.get(i);
                pageResultList.add(dto);
            } else {
                break;
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("totalSize", resultList.size());
        map.put("list", pageResultList);
        return map;
    }

    public static boolean isValidGrade(String gradeValue) {
        if (gradeValue == null) {
            return false;
        }
        if (gradeValue.equals("B") || gradeValue.equals("B+")
                || gradeValue.equals("C") || gradeValue.equals("A")
                || gradeValue.equals("A+") || gradeValue.equals("D")) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isValidCulture(String cultureValue) {
        if (cultureValue == null) {
            return false;
        }
        if (cultureValue.equals("2级") || cultureValue.equals("3级")
                || cultureValue.equals("1级") || cultureValue.equals("4级")) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * Date转LocalDate
     *
     * @param date
     */
    public static LocalDate date2LocalDate(Date date) {
        if (null == date) {
            return null;
        }
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }


    public static Map<String, String> getSeasonPeriod(String seasonName) {
        try {
            int year = Integer.parseInt(seasonName.substring(0, 4));
            String season = seasonName.substring(4, 6);
            String beginDay = "";
            String endDay = "";
            if (season.equalsIgnoreCase("Q1")) {
                beginDay = year + "-01-01";
                endDay = year + "-04-01";
            } else if (season.equalsIgnoreCase("Q2")) {
                beginDay = year + "-04-01";
                endDay = year + "-07-01";
            } else if (season.equalsIgnoreCase("Q3")) {
                beginDay = year + "-07-01";
                endDay = year + "-10-01";
            } else if (season.equalsIgnoreCase("Q4")) {
                beginDay = year + "-10-01";
                endDay = (year + 1) + "-01-01";
            }
            Map<String, String> resultMap = new HashMap<>();
            resultMap.put("beginDay", beginDay);
            resultMap.put("endDay", endDay);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("获取季度开始结束时间出错。");
        }
    }

    /**
     * //根据季度的起始时间获取季度名称
     *
     * @param dateStr:2021-01-01->2021Q1;2020-10-01->2020Q4
     */
    public static String getPeriodName(String dateStr) {
        try {
            int year = Integer.parseInt(dateStr.substring(0, 4));
            String mounth = dateStr.substring(5,7);
            String periodName="";
            switch (mounth) {
                case "01":
                    periodName = year + "Q1";
                    break;
                case "04":
                    periodName = year + "Q2";
                    break;
                case "07":
                    periodName = year + "Q3";
                    break;
                case "10":
                    periodName = year + "Q4";
                    break;
            }
            return periodName;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("获取季度名称出错。");
        }
    }

    /**
     * //季度名称链表排序
     * //个数大于4时，只返回前4个
     * @param periodNameList:2021Q1；2020Q4...
     */
    public static List<String> sortedPeridName(List<String> periodNameList){
        List<String> newList = new ArrayList<>();
        for (String param : periodNameList) {
            String newParam = param.replace("Q", "0");
            newList.add(newParam);
        }
        String[] arr = newList.toArray(new String[newList.size()]);
        int[] intArr = new int[arr.length];
        for (int i = 0; i < intArr.length; i++) {
            intArr[i] = Integer.parseInt(arr[i]);
        }
        Arrays.sort(intArr);
        List <String> newPeriodNameList=new ArrayList<>();
        for (int i = intArr.length-1; i >=0; i--) {
            String temp=String.valueOf(intArr[i]);
            StringBuilder newPeriodName=new StringBuilder(temp).replace(4,5,"Q");
            newPeriodNameList.add(newPeriodName.toString());
        }
        List <String> tempList=new ArrayList<>();
        if(newList.size()<=4){
            return newPeriodNameList;
        }else {
           tempList = newPeriodNameList.subList(0,4);
        }
        return tempList;
    }

    public static String[] getLastSeasonsByNum(Date date, int genNum) {
//        List<MutiSelectDTO> resultList = new ArrayList<>();
        int index = 0;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        boolean yearFlag = false;
        String[] seasonArray = new String[genNum];
        do {
            if (index == 0) {
                calendar.add(Calendar.MONTH, -3);
                index++;
                continue;
            }

            int year = calendar.get(Calendar.YEAR);
            int m = calendar.get(Calendar.MONTH);
            String quarter = "";
//            if (yearFlag) {
//                MutiSelectDTO dto = new MutiSelectDTO(year + "", year + "", 0);
//                resultList.add(dto);
//                yearFlag = false;
//            }
            if (m >= Calendar.JANUARY && m <= Calendar.MARCH) {
                quarter = "Q1";
                yearFlag = true;
            }
            if (m >= Calendar.APRIL && m <= Calendar.JUNE) {
                quarter = "Q2";
            }
            if (m >= Calendar.JULY && m <= Calendar.SEPTEMBER) {
                quarter = "Q3";
            }
            if (m >= Calendar.OCTOBER && m <= Calendar.DECEMBER) {
                quarter = "Q4";
            }

            seasonArray[index - 1] = year + quarter;
//            MutiSelectDTO dto = new MutiSelectDTO(year + quarter, year + quarter, 0);
//            resultList.add(dto);
            calendar.add(Calendar.MONTH, -3);
            index++;
        } while (index <= genNum);
        return seasonArray;
    }

    //将文件转换成Byte数组
    public static byte[] getBytesByFile(File file) {
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            byte[] data = bos.toByteArray();
            bos.close();
            return data;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getIp(HttpServletRequest httpServletRequest) {
        //获取客户端的真实IP
        String realIP = httpServletRequest.getHeader("X-Real-IP");
        String forwardedFor = httpServletRequest.getHeader("X-Forwarded-For");
        log.info("-------------------------------------------------------X-Real-IP="+realIP+";X-Forwarded-For="+forwardedFor);
        if (StringUtils.hasText(realIP)) {
            return realIP;
        }
        //String forwardedFor = httpServletRequest.getHeader("X-Forwarded-For");
        if (StringUtils.hasText(forwardedFor)) {
            return forwardedFor;
        } else {
            return httpServletRequest.getRemoteAddr();
        }
    }

    public static Date addMonth(Date origDate, int addNum) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(origDate);
        calendar.add(Calendar.MONTH, addNum);
        return calendar.getTime();
    }

    public static Date addDay(Date origDate, int addNum) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(origDate);
        calendar.add(Calendar.DAY_OF_MONTH, addNum);
        return calendar.getTime();
    }

    /**
     * 当前季度的开始时间,即2012-03-31 23:59:59
     *
     * @return
     */
    public static Date getCurrentQuarterStartTime() {
        Calendar c = Calendar.getInstance();
        int currentMonth = c.get(Calendar.MONTH) + 1;
        SimpleDateFormat longSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat shortSdf = new SimpleDateFormat("yyyy-MM-dd");
        Date now = null;
        try {
            if (currentMonth >= 1 && currentMonth <= 3)
                c.set(Calendar.MONTH, 0);
            else if (currentMonth >= 4 && currentMonth <= 6)
                c.set(Calendar.MONTH, 3);
            else if (currentMonth >= 7 && currentMonth <= 9)
                c.set(Calendar.MONTH, 4);
            else if (currentMonth >= 10 && currentMonth <= 12)
                c.set(Calendar.MONTH, 9);
            c.set(Calendar.DATE, 1);
            now = longSdf.parse(shortSdf.format(c.getTime()) + " 00:00:00");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return now;
    }

    /**
     * 当前季度的结束时间,即2012-03-31 23:59:59
     *
     * @return
     */
    public static Date getCurrentQuarterEndTime() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(getCurrentQuarterStartTime());
        cal.add(Calendar.MONTH, 3);
        return cal.getTime();
    }


    public static String nullToEmpty(String str) {
        if (str == null || str.trim().equals("")) {
            return "";
        }
        return str;
    }

    public static double formatDecimal(double num) {
        return new BigDecimal(num).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    public static String divisionReturnPercentValue(int a, int b) {
        return new java.text.DecimalFormat("0.0").format((float) a * 100 / b) + "%";
    }

    public static String divisionReturnPercentValue(int a, int b, int weight, int preWeight) {
        return new java.text.DecimalFormat("0.0").format((float) a * weight / b + preWeight) + "%";
    }

    public static String divisionReturnPercentValueNoChar(int a, int b, int weight, int preWeight) {
        return new java.text.DecimalFormat("0.0").format((float) a * weight / b + preWeight);
    }

    public static double formatDecimal(double num, int digitNum) {
        if (digitNum < 0) {
            digitNum = 0;
        }
        return new BigDecimal(num).setScale(digitNum, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    public static Integer nullToZero(Integer num) {
        if (num == null) {
            return 0;
        }
        return num;
    }

    public static BigDecimal nullToZero(BigDecimal num) {
        if (num == null) {
            return new BigDecimal(0);
        }
        return num;
    }

    public static String getCurMonth() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        return sdf.format(new Date());
    }

    public static String getDateMonth(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        return sdf.format(date);
    }

    public static String contactListStrings(List<String> strList) {
        return contactListStrings(strList, ",");
    }

    public static String contactListStrings(Set<String> strList) {
        return contactListStrings(strList, ",");
    }

    public static List<String> parseApprovalUserIds(String approvalUserIds) {
        if (StringUtils.isEmpty(approvalUserIds)) {
            return new ArrayList<>();
        } else {
            List<String> resultList = new ArrayList<>();
            if (approvalUserIds.indexOf(",") >= 0) {
                for (String workerId : approvalUserIds.split(",")) {
                    if (!StringUtils.isEmpty(workerId)) {
                        resultList.add(workerId);
                    }
                }
            } else {
                resultList.add(approvalUserIds);
            }
            return resultList;
        }
    }

    public static String contactListStrings(Collection<String> strList, String contactWord) {
        if (strList == null || strList.size() == 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        strList.forEach(str -> sb.append(str).append(contactWord));
        int contactWordLength = contactWord.length();
        String result = sb.toString();
        return result.substring(0, result.length() - contactWordLength);
    }

    

    public static int getBetweenValue(String v1, String v2) {
        return getBetweenValue(getValueByStageName(v1), getValueByStageName(v2));
    }

    public static int getBetweenValue(int v1, int v2) {
        if (v1 > v2) {
            return v1 - v2;
        } else {
            return v2 - v1;
        }
    }

    public static int getValueByStageName(String inputName) {
        if (StringUtils.isEmpty(inputName)) {
            throw new AppBusinessException("传入的绩效等级为空");
        }
        if (inputName.equals("A+")) {
            return 1;
        } else if (inputName.equals("A")) {
            return 2;
        } else if (inputName.equals("B+")) {
            return 3;
        } else if (inputName.equals("B")) {
            return 4;
        } else if (inputName.equals("C")) {
            return 5;
        } else if (inputName.equals("D")) {
            return 6;
        }
        throw new AppBusinessException("传入的绩效等级格式不正确");
    }




    public static String getPercent(double x, double total, int digitScale) {
        double f = x * 100 / total;
        BigDecimal bg = new BigDecimal(f);
        double f1 = bg.setScale(digitScale, BigDecimal.ROUND_HALF_UP).doubleValue();
        return f1 + "";
    }

    public static String getPostData(CustomHttpServletRequestWrapper requestWrapper) {

        String result = null;
        try {
            result = new String(requestWrapper.getBody(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (result != null && result.length() > 1000) {
            return result.substring(0, 1000);
        }
        return result;
    }

    public static void zipFiles(List<File> srcFiles, File zipFile) {
        if (!zipFile.exists()) {
            try {
                zipFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        FileOutputStream fileOutputStream = null;
        ZipOutputStream zipOutputStream = null;
        FileInputStream fileInputStream = null;

        try {
            fileOutputStream = new FileOutputStream(zipFile);
            zipOutputStream = new ZipOutputStream(fileOutputStream);
            ZipEntry zipEntry = null;
            for (int i = 0; i < srcFiles.size(); i++) {
                fileInputStream = new FileInputStream(srcFiles.get(i));
                zipEntry = new ZipEntry(srcFiles.get(i).getName());
                zipOutputStream.putNextEntry(zipEntry);
                int len;
                byte[] buffer = new byte[1024];
                while ((len = fileInputStream.read(buffer)) > 0) {
                    zipOutputStream.write(buffer, 0, len);
                }
            }
            zipOutputStream.closeEntry();
            zipOutputStream.close();
            fileInputStream.close();
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static boolean isEmail(String email) {
        if (null == email || "".equals(email)) {
            return false;
        }
        String regEx1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        Pattern p = Pattern.compile(regEx1);
        Matcher m = p.matcher(email);
        return m.matches();
    }

    public static boolean isPhoneNum(String str) {
        return isMobilePhone(str) || isTelephone(str);
    }
    /**
     * 大陆手机号码11位数，匹配格式：前三位固定格式+后8位任意数
     * 此方法中前三位格式有：
     * 13+任意数
     * 145,147,149
     * 15+除4的任意数(不要写^4，这样的话字母也会被认为是正确的)
     * 166
     * 17+3,5,6,7,8
     * 18+任意数
     * 198,199
     */
    public static boolean isMobilePhone(String str) {
        String regExp = "^((13[0-9])|(14[0-9])|(15[0-9])|(166)|(17[0-9])|(18[0-9])|(19[0-9]))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }

    /**
     * 固定电话
     */
    public static boolean isTelephone(String str) {
        String regExp = "0\\d{2,3}[-]?\\d{7,8}|0\\d{2,3}\\s?\\d{7,8}";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }

    /*
     *校验银行卡是否符合Luhm算法，
     */
    public static boolean checkBankCard(String cardId) {
        if (!cardId.matches("^\\d{8,19}$")) {
            return false;
        }
        char[] array = cardId.toCharArray();
        int n = array.length;
        int sum = 0;
        for (int i = n; i >= 1; i--) {
            int c = array[n - i] - '0';
            if (i % 2 == 0) {
                c *= 2;
            }
            sum = sum + c / 10 + c % 10;
        }
        if (sum % 10 == 0) {
            return true;
        } else {
            return false;
        }
    }

    public static List<Map<String,String>> addressResolution(String address){
        String regex="(?<province>[^省]+自治区|.*?省|.*?行政区|.*?市)(?<city>[^市]+自治州|.*?地区|.*?行政单位|.+盟|市辖区|.*?市|.*?县)(?<county>[^县]+县|.+区|.+市|.+旗|.+海域|.+岛)?(?<town>[^区]+区|.+镇)?(?<village>.*)";
        Matcher m=Pattern.compile(regex).matcher(address);
        String province=null,city=null,county=null,town=null,village=null;
        List<Map<String,String>> table=new ArrayList<Map<String,String>>();
        Map<String,String> row=null;
        while(m.find()){
            row=new LinkedHashMap<String,String>();
            province=m.group("province");
            row.put("province", province==null?"":province.trim());
            city=m.group("city");
            row.put("city", city==null?"":city.trim());
            county=m.group("county");
            row.put("county", county==null?"":county.trim());
            town=m.group("town");
            row.put("town", town==null?"":town.trim());
            village=m.group("village");
            row.put("village", village==null?"":village.trim());
            table.add(row);
        }
        return table;
    }

    /**
     * 验证邮箱
     *
     * @param email
     * @return
     */
    public static boolean checkEmail(String email) {
        String regex = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
        ///\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
        return check(email, regex);
    }

    /**
     * 验证手机号码
     *
     * 移动号码段:139、138、137、136、135、134、150、151、152、157、158、159、182、183、187、188、147
     * 联通号码段:130、131、132、136、185、186、145
     * 电信号码段:133、153、180、189
     *
     * @param cellphone
     * @return
     */
    public static boolean checkCellphone(String cellphone) {
        String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8}$";
        return check(cellphone, regex);
    }

    public static boolean check(String str, String regex) {
        boolean flag = false;
        try {
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(str);
            flag = matcher.matches();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    //","链接的字符串去重；
    public  static String moveSame(String str){
      List<String> strList = Arrays.stream(str.split(",")).collect(Collectors.toList());
      strList.removeIf(Objects::isNull);
      List<String> tempList=strList.stream().distinct().collect(Collectors.toList());
      return String.join(",",tempList);
    }

    public static boolean checkHtml(String html) {
        return html.contains("onload") || html.contains("onerror") || html.contains("onclick") || html.contains("script") || html.contains("alert") || html.contains(".js");
    }

    public static Integer judgeStr(String keyWords) {
        Pattern pattern1 = Pattern.compile("[0-9]*");
        Matcher matcher1 = pattern1.matcher(keyWords);
        if (matcher1.matches()) {
            return 1;
        } else {
            Pattern pattern2 = Pattern.compile("[a-zA-Z]+$");
            Matcher matcher2 = pattern2.matcher(keyWords);
            if (matcher2.matches()) {
                return 2;
            } else {
                Pattern pattern3 = Pattern.compile("[\\u4e00-\\u9fa5]{0,}$");
                Matcher matcher3 = pattern3.matcher(keyWords);
                if (matcher3.matches()) {
                    return 3;
                } else {
                    return -1;
                }
            }
        }

    }

    /**
     * @param userRoleCh
     * @return userRole
     */
    public static String getUserRoleCh(String userRoleCh){
        StringBuffer userRole = new StringBuffer();
        for (String roleCh : userRoleCh.split(",")) {
            switch (userRoleCh){
                case "管理员":
                    userRole.append(BusiEnumDefine.USER_ROLE_ADMIN + ",") ;
                    break;
                case "HRBP":
                    userRole.append(BusiEnumDefine.USER_ROLE_BP + ",");
                    break;
                case "部门接口人":
                    userRole.append(BusiEnumDefine.USER_ROLE_DEPT_CONTACTOR + ",");
                    break;
                case "干部部长":
                    userRole.append(BusiEnumDefine.USER_ROLE_GBBZ + ",");
                    break;
                case "小任务管理员":
                    userRole.append(BusiEnumDefine.USER_ROLE_TASK_MANAGER + ",");
                    break;
                case "CHRO":
                    userRole.append(BusiEnumDefine.USER_ROLE_CHRO + ",");
                    break;
           /* case "部门主管":
                userRole = BusiEnumDefine.USER_ROLE_DEPT_MANAGER;
                break;
            case "新员工":
                userRole = BusiEnumDefine.USER_ROLE_WORKER;
                break;
            case "流程审批人":
                userRole = BusiEnumDefine.USER_ROLE_APPROVER;
                break;*/
            }
        }
        return userRole.toString().substring(0, userRole.toString().length() - 1);
    }

    /**
     * 工号转化成对实际工号
     *
     * @param empCode 8位工号
     * @author h24002
     * @date 2022/6/24
     */
    public static String GetEmpCodeTo5(String empCode) {
        int workerCode = NumberUtils.toInt(empCode);
        if (workerCode <= 9999) {
            return String.format("%05d", workerCode);
        } else {
            return Integer.toString(workerCode);
        }
    }

    /**
     * 补零
     * @param empCode
     * @return
     */
    public static String GetEmpCodeToZero(String empCode) {
        int workerCode = NumberUtils.toInt(empCode);
        if (workerCode <= 9999999) {
            return String.format("%08d", workerCode);
        } else {
            return Integer.toString(workerCode);
        }
    }

    public static Integer judgeTypeOfferWorker(TbOfferWorker worker){
        if (worker.getProjectWorkerFlag().contains("1")) {
            // 项目制员工
            return 1;
        }
        if (worker.getInType().contains("校招")) {
            // 应届生
            return 2;
        } else {
            // 普通员工
            return 3;
        }

    }

}
